package com.raja.servingStation.common.redis;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数据类型判断和比较
 * @author Administrator
 *
 */
public class DataUtil {
	public static final Pattern NUMBER_PATTERN = Pattern.compile("^(-?\\d+)(\\.\\d+)?$");
	public static final Pattern INTEGER_PATTERN = Pattern.compile("^-?[\\d]+$");
	public static final Pattern DATE_PATTERN = Pattern.compile("^(\\d{4})\\-(\\d{2})\\-(\\d{2})$");
	public static final Pattern TIME_PATTERN = Pattern.compile("^(\\d{4})\\-(\\d{2})\\-(\\d{2})\\s(\\d{2}):(\\d{2}):(\\d{2})$");
	
	/**
	 * 判断字符串是否为空
	 * @param param
	 * @return
	 */
	public static boolean isEmpty(String param) {
		return param == null || param.trim().length()==0;
	}

	/**
	 * 判断字符串不为空
	 * @param param
	 * @return
	 */
	public static boolean isNotEmpty(String param) {
		return param != null && param.trim().length()!=0;
	}

	/**
	 * 判断是否为数字
	 * @param param
	 * @return
	 */
	public static boolean isNumber(String param) {
		if (param == null)
			return false;
		Matcher m = NUMBER_PATTERN.matcher(param);
		return (m.find());
	}

	/**
	 * 判断是否为整型数字
	 * @param param
	 * @return
	 */
	public static boolean isInteger(String param) {
		if (param == null)
			return false;
		Matcher m = INTEGER_PATTERN.matcher(param);

		return (m.find());
	}

	/**
	 * 判断是否为日期字符串（格式如：2014-04-01）
	 * @param param
	 * @return
	 */
	public static boolean isDate(String param) {
		if (param != null) {
			Matcher m = DATE_PATTERN.matcher(param);
			if (m.find())
				return true;
		}
		return false;
	}

	/**
	 * 判断是否为时间字符串（格式如：2014-04-01 12:00:00）
	 * @param param
	 * @return
	 */
	public static boolean isTime(String param) {
		if (param != null) {
			Matcher m = TIME_PATTERN.matcher(param);
			if (m.find())
				return true;
		}
		return false;
	}
	
	public static String getJSONStringByList(List<?> list){
		return getJSONStringByList(list,null);
	}
	
	/**
	 * 指定字段获取List的JSON格式数据
	 * @author 程赞达
	 * @param list 需要被转换的集合
	 * @param fields 需要获取的字段
	 * @return String
	 */
	public static String getJSONStringByList(List<?> list,List<String> fields){
		if(list==null){
			return null;
		}
		if(fields==null){
			fields = new ArrayList<String>();
			fields.add("id");
			fields.add("name");
		}
		StringBuilder sb= new StringBuilder();
		sb.append("[");
		for(int i=0;i<list.size();i++){
			Object obj=list.get(i);
			Class<?> c=obj.getClass();
			sb.append("{");
			for(int j=0;j<fields.size();j++){
				String field = fields.get(j);
				try {
					Method m = c.getMethod("get"+field.substring(0, 1).toUpperCase()+field.substring(1), null);
					sb.append("\""+field+"\":\""+m.invoke(obj, null)+"\"");
				} catch (Exception e) {
				}
				if(j!=fields.size()-1){
					sb.append(",");
				}
			}
			sb.append("}");
			if(i!=list.size()-1){
				sb.append(",");
			}
		}
		sb.append("]");
		return sb.toString();
	}
	
	/**
	 * JSON字符串转换成对象集合(只支持6种基本数据类型)
	 * @author 程赞达
	 * @param c 集合的对象
	 * @param json 需要被转换的字符串
	 * @return List
	 */
	public static List<?> getObjectByJSONString(Class<?> c,String json) throws Exception{
		if(json.length()<=2 && json.contains("{")==false){
			return null;
		}
		json=","+json.substring(1, json.length()-1);
		String[] ss=json.split("}");
		List<Object> list=new ArrayList<Object>(); 
		Field[] f = c.getDeclaredFields();
		for (int i = 0; i < ss.length; i++) {
			String [] arr=ss[i].substring(2).replaceAll("\"", "").split(",");
			Map<String,String> map = getMapByArray(arr);
			Object o = c.newInstance();
			for (int j = 0; j < f.length;j++) {
				String name = f[j].getName();
				String value = map.get(name);
				if(value != null){
					String setName = "set"+name.substring(0, 1).toUpperCase()+name.substring(1);
					Class<?> ctype = f[j].getType();
					Object val = null;
					if(ctype.equals(String.class)){
						val = value.toString();
					}else if(ctype.equals(Integer.class)){
						val = Integer.parseInt(value);
					}else if(ctype.equals(Long.class)){
						val = Long.parseLong(value);
					}else if(ctype.equals(Double.class)){
						val = Double.parseDouble(value);
					}else if(ctype.equals(Float.class)){
						val = Float.parseFloat(value);
					}else if(ctype.equals(Boolean.class)){
						val = Boolean.parseBoolean(value);
					}else if(ctype.equals(Short.class)){
						val = Short.parseShort(value);
					}
					if(val != null){
						o.getClass().getMethod(setName,ctype).invoke(o,val);
					}
				}
			}
			list.add(o);
		}
		return list;
	}
	
	/**
	 * 一个单元的json字符串转换成MAP对象
	 * @methodName: getMapByArray  
	 * @param: 
	 * @author: 程赞达
	 * @date: Jul 16, 2011 8:35:23 PM
	 * @return:    
	 * @throws:
	 */
	public static Map<String,String> getMapByArray(String[] arr){
		Map<String,String> map=new HashMap<String,String>();
		for (int i = 0; i < arr.length; i++) {
			int pos=arr[i].indexOf(":");
			map.put(arr[i].substring(0, pos), arr[i].substring(pos+1));
		}
		return map;
	}
	
	/**
	 * 数组转换成集合
	 * @param String[]
	 * @return
	 */
	public static List<String> arrayToList(String[] strs) {
		List<String> list = new ArrayList<String>();
		if(strs!=null && strs.length>0) {
			for(String str:strs) {
				list.add(str);
			}
		}
		return list;
	}
	
	/**
	 * List深拷贝
	 * @param src
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static List deepCopy(List src) throws IOException, ClassNotFoundException {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(byteOut);
		out.writeObject(src);
		ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut
				.toByteArray());
		ObjectInputStream in = new ObjectInputStream(byteIn);
		List dest = (List) in.readObject();
		return dest;
	}   
	
	/**
	 * 字符串转换为short
	 * @param val 原始值
	 * @return 返回值>0，表示成功，失败返回0 
	 */
	public static short parseShort(String val) {
		short result = 0;
		
		try {
			result = Short.parseShort(val);
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * 字符串转换为short，可以设置默认值
	 * @param val 原始值
	 * @param def 默认值
	 * @return 返回值>0，表示成功，失败返回默认值
	 */
	public static short parseShortDef(String val, short def) {
		short result = def;
		
		try {
			result = Short.parseShort(val);
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * 字符串转换为int
	 * @param val 原始值
	 * @return 返回值>0，表示成功，失败返回0 
	 */
	public static int parseInt(String val) {
		int result = 0;
		
		try {
			result = Integer.parseInt(val);
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * 字符串转换为int，可以设置默认值
	 * @param val 原始值
	 * @param def 默认值
	 * @return 返回值>0，表示成功，失败返回默认值
	 */
	public static int parseIntDef(String val, int def) {
		int result = def;
		
		try {
			result = Integer.parseInt(val);
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * 字符串转换为long
	 * @param val 原始值
	 * @return 返回值>0，表示成功，失败返回0 
	 */
	public static long parseLong(String val) {
		long result = 0;
		
		try {
			result = Long.parseLong(val);
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * 字符串转换为long，可以设置默认值
	 * @param val 原始值
	 * @param def 默认值
	 * @return 返回值>0，表示成功，失败返回默认值
	 */
	public static long parseLongDef(String val, long def) {
		long result = def;
		
		try {
			result = Long.parseLong(val);
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * 字符串转换为double
	 * @param val 原始值
	 * @return 返回值>0，表示成功，失败返回0 
	 */
	public static double parseDouble(String val) {
		double result = 0;
		
		try {
			result = Double.parseDouble(val);
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * 字符串转换为double，可以设置默认值
	 * @param val 原始值
	 * @param def 默认值
	 * @return 返回值>0，表示成功，失败返回默认值
	 */
	public static double parseDoubleDef(String val, double def) {
		double result = def;
		
		try {
			result = Double.parseDouble(val);
		} catch (Exception e) {
			
		}
		return result;
	}
	
	/**
	 * Integer转换成short
	 * @param val
	 * @return
	 */
	public static short toShortValue(Integer val) {
		short result = 0;
		
		if (val != null) {
			try {
				result = val.shortValue();
			} catch (Exception e) {

			}
		}
		return result;
	}
	
	/**
	 * Integer转换成byte
	 * @param val
	 * @return
	 */
	public static byte toByteValue(Integer val) {
		byte result = 0;
		
		if (val != null) {
			try {
				result = val.byteValue();
			} catch (Exception e) {

			}
		}
		return result;
	}
	
	/**
	 * Long转换成int
	 * @param val
	 * @return
	 */
	public static int toIntValue(Long val) {
		int result = 0;
		
		if (val != null) {
			try {
				result = val.intValue();
			} catch (Exception e) {

			}
		}
		return result;
	}

	/**
	 * 保留小数位数到指定位数
	 * @param value	要处理的值
	 * @param digit 小数位数
	 * @return
	 */
	/*public static double convertDecimal(double value,int digit){
		BigDecimal b = new BigDecimal(value);
		double retValue = b.setScale(digit, BigDecimal.ROUND_HALF_UP).doubleValue();
		return retValue;
	}*/
	
	/**
	 * 保留小数位数到指定位数
	 * @param value
	 * @param digit
	 * @return
	 */
	public static String convertDecimalToStr(double value,int digit){
		BigDecimal b = new BigDecimal(value);
		String retValue = b.setScale(digit, BigDecimal.ROUND_HALF_UP).toPlainString();
		return retValue;
	}
	
	/**
	 * 判断一个数是否在指定范围内
	 * @param value	要判断的值
	 * @param start	最小值
	 * @param end	最大值
	 * @param type	类型:1:不包含 2:包含
	 * @return
	 */
	public static boolean withinRange(long value,long start,long end,int type){
		if (type == 2) {
			if (value >= start && value <= end) {
				return true;
			}else{
				return false;
			}
		}else{
			if (value > start && value < end) {
				return true;
			}else{
				return false;
			}
		}
	}
	
	public static void main(String[] args) {
		int num1 = 7;  
		  
        int num2 = 9;  
  
        // 创建一个数值格式化对象  
  
        NumberFormat numberFormat = NumberFormat.getInstance();  
  
        // 设置精确到小数点后2位  
  
        numberFormat.setMaximumFractionDigits(2);  
  
        String result = numberFormat.format((float) num1 / (float) num2 * 100);  
  
        System.out.println("num1和num2的百分比为:" + result + "%");
	}
	
	public static final String NO_DATA = "-";
	
	/**
	 * 边界值类型
	 */
	public static final int BYTE_BOUNDARY_DWORD = 1;
	public static final int BYTE_BOUNDARY_WORD = 2;
	public static final int BYTE_BOUNDARY_BYTE_FF = 3;
	public static final int BYTE_BOUNDARY_BYTE = 4;
	
	/**
	 * 判断value是否达到边界值
	 * @param value
	 * @param type
	 * @return
	 */
	public static boolean byteBoundary(long value,int type){
		boolean result = false;
		
		switch (type) {
		case BYTE_BOUNDARY_DWORD:
			result = (value == 0xFFFFFFFFL || value == 0xFFFFFFFF
					|| value == 0xFFFFFFFEL || value == 0xFFFFFFFE);
			break;
		case BYTE_BOUNDARY_WORD:
			result = (value == 0xFFFFL || value == 0xFFFF 
					|| value == 0xFFFEL || value == 0xFFFE);
			break;	
		case BYTE_BOUNDARY_BYTE_FF:
			result = (value == 0xFFL || value == 0xFF);
			break;
		case BYTE_BOUNDARY_BYTE:
			result = (value == 0xFEL || value == 0xFE || value == 0xFFL
					|| value == 0xFF);
			break;
		default:
			break;
		}
		
		return result;
		
	}
	
	/**
	 * 修正参数乱码 
	 * @param str
	 * @return
	 */
	public static String encodeStr(String str) {  
        try {  
            return new String(str.getBytes("ISO-8859-1"), "UTF-8");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
            return null;  
        }  
    }
	
	/**
	 * 计算进度
	 * @param total	总数
	 * @param count	当前执行了多少
	 * @param percent 占比
	 * @return
	 */
	public static String calProgress(int total,int count,double percent){
		// 创建一个数值格式化对象  
        NumberFormat numberFormat = NumberFormat.getInstance();  
        // 设置精确到小数点后2位  
        numberFormat.setMaximumFractionDigits(0);  
  
        String progress = numberFormat.format(((float)count/(float)total*100)*percent);  
		//int progress = (count/total)*100;
		return progress;
	}
	
	/**
	 * 去重
	 * @param data
	 * @return
	 */
	public static List<String> deDuplication(List<String> data){
		Set<String> set = new HashSet<String>();
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < data.size(); i++) {
			set.add(data.get(i));
		}
		Iterator<String> it = set.iterator();  
		while (it.hasNext()) { 
		  result.add(it.next());
		}
		return result;
	}
	
	/**
	 * 去重
	 * @param data	Integer类型数组
	 * @return
	 */
	public static List<Integer> deDuplicationInt(List<Integer> data){
		Set<Integer> set = new HashSet<Integer>();
		List<Integer> result = new ArrayList<Integer>();
		for (int i = 0; i < data.size(); i++) {
			set.add(data.get(i));
		}
		Iterator<Integer> it = set.iterator();  
		while (it.hasNext()) { 
		  result.add(it.next());
		}
		return result;
	}
}
